<template>
  <div class="expert-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>专家管理</span>
          <el-button type="primary" @click="handleAdd">添加专家</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="科室">
          <el-input v-model="searchForm.department" placeholder="请输入科室" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="接诊" value="1" />
            <el-option label="停诊" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 专家表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="title" label="职称" />
        <el-table-column prop="department" label="科室" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '接诊' : '停诊' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '停诊' : '接诊' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 专家表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加专家' : '编辑专家'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="form.title" placeholder="请输入职称" />
        </el-form-item>
        <el-form-item label="科室" prop="department">
          <el-input v-model="form.department" placeholder="请输入科室" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input 
            v-model="form.introduction" 
            type="textarea" 
            :rows="3"
            placeholder="请输入专家简介" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">接诊</el-radio>
            <el-radio :label="0">停诊</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getExpertList, 
  getExpertDetail, 
  addExpert, 
  updateExpert, 
  deleteExpert, 
  updateExpertStatus 
} from '@/api/expert'

// 搜索表单
const searchForm = reactive({
  username: '',
  name: '',
  department: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const formRef = ref(null)
const form = reactive({
  id: null,
  username: '',
  password: '',
  name: '',
  title: '',
  department: '',
  introduction: '',
  status: 1
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入职称', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入科室', trigger: 'blur' }
  ],
  introduction: [
    { required: true, message: '请输入专家简介', trigger: 'blur' }
  ]
}

// 获取专家列表
const fetchExpertList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    console.log('请求参数:', params)
    const res = await getExpertList(params)
    console.log('API响应:', res)
    
    // 直接使用返回的分页数据
    if (res && typeof res === 'object') {
      tableData.value = res.records || []
      total.value = res.total || 0
      currentPage.value = res.current || 1
      pageSize.value = res.size || 10
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error('获取专家列表失败')
      console.error('意外的响应格式:', res)
    }
  } catch (error) {
    console.error('获取专家列表失败:', error)
    console.error('错误详情:', error.response || error)
    tableData.value = []
    total.value = 0
    ElMessage.error(error.response?.data?.message || '获取专家列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchExpertList()
}

// 重置
const handleReset = () => {
  searchForm.username = ''
  searchForm.name = ''
  searchForm.department = ''
  searchForm.status = ''
  handleSearch()
}

// 添加专家
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = null
  form.username = ''
  form.password = ''
  form.name = ''
  form.title = ''
  form.department = ''
  form.introduction = ''
  form.status = 1
  dialogVisible.value = true
}

// 编辑专家
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  try {
    // 清空表单
    form.id = null
    form.username = ''
    form.password = ''
    form.name = ''
    form.title = ''
    form.department = ''
    form.introduction = ''
    form.status = 1

    const res = await getExpertDetail(row.id)
    console.log('获取专家详情响应:', res)
    
    if (res.data) {
      // 设置新数据
      Object.assign(form, res.data)
      // 清空密码字段，编辑时不显示密码
      form.password = ''
      dialogVisible.value = true
    } else {
      throw new Error('专家数据为空')
    }
  } catch (error) {
    console.error('获取专家详情失败:', error)
    console.error('错误详情:', error.response || error)
    ElMessage.error(error.message || '获取专家详情失败')
  }
}

// 切换专家状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  ElMessageBox.confirm(
    `确定要${row.status === 1 ? '停诊' : '接诊'}该专家吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateExpertStatus(row.id, newStatus)
      ElMessage.success(`${row.status === 1 ? '停诊' : '接诊'}成功`)
      row.status = newStatus
    } catch (error) {
      console.error('更新状态失败:', error)
      ElMessage.error('操作失败')
    }
  })
}

// 删除专家
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该专家吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteExpert(row.id)
      ElMessage.success('删除成功')
      fetchExpertList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addExpert(form)
          ElMessage.success('添加成功')
        } else {
          await updateExpert(form)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        fetchExpertList()
      } catch (error) {
        console.error('保存失败:', error)
        if (error.response?.data?.code === 41000) {
          ElMessage.error('用户名已存在')
        } else {
          ElMessage.error('保存失败')
        }
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchExpertList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchExpertList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchExpertList()
})
</script>

<style scoped>
.expert-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 